package com.cloudptt.api.product.timer;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;


public class RollbackTimer
{
	private final static int MsgId_Rollback = 1;
//	private Context ctx = null;
	private int timerId = 0;
	private Timer timer = null;
	private  Handler handler = null;
	private IRollback rollback = null;

	public RollbackTimer(Context ctx,int timerId,int seconds,IRollback rollback)
	{
		this.timerId = timerId;
		if(ctx != null)
		{
			this.handler = new RollbackHandler(ctx.getMainLooper());
		}
		else
		{
			this.handler = new RollbackHandler();
		}
		this.timer = new Timer();  
		TimerTask task = new RollbackTask();
		this.timer.schedule(task, seconds * 1000); 
		
		this.rollback = rollback;
	}
	
	public RollbackTimer(int timerId,int seconds,IRollback rollback)
	{
		this.timerId = timerId;
		this.handler = new RollbackHandler();
		this.timer = new Timer();  
		TimerTask task = new RollbackTask();
		this.timer.schedule(task, seconds * 1000); 
		
		this.rollback = rollback;
	}
	public void cancelTimer()
	{
		if(handler != null)
		{
			handler.removeMessages(MsgId_Rollback);
		}
		if(this.timer != null)
		{
			this.timer.cancel();
			this.timer = null;
		}
	}
	public void restartTimer(int seconds)
	{
		if(handler != null)
		{
			handler.removeMessages(MsgId_Rollback);
		}
		if(this.timer != null)
		{
			this.timer.cancel();
			this.timer = null;
		}
		this.timer = new Timer();
		TimerTask task = new RollbackTask();
		this.timer.schedule(task, seconds * 1000);
	}
	
	class RollbackTask extends TimerTask 
	{  
		@Override  
		public void run() {  
			// 闇�瑕佸仛鐨勪簨:鍙戦�佹秷鎭�  
//			Looper.prepare();
			cancelTimer();
			if(handler != null)
			{
				Message msg = handler.obtainMessage(MsgId_Rollback);
				msg.sendToTarget();
			}
			
//			Looper.loop();
		}  
	}
	
	class RollbackHandler extends Handler
	{
		public RollbackHandler(Looper looper)
		{
			super(looper);
		}
		public RollbackHandler()
		{
			super();
		}
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == MsgId_Rollback)
			{
				rollback.rollback(timerId);
			}
		}
	}
}
